package com.ys.everydaynews.base

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.ys.everydaynews.R
import com.ys.everydaynews.mvp.presenter.BasePresenter
import com.ys.everydaynews.mvp.view.BaseView
import com.ys.everydaynews.ui.main.model.EventModel
import com.ys.everydaynews.utils.SharedPreferencesUtils
import com.ys.everydaynews.utils.StatusBarUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseActivity<V, P : BasePresenter<V>, DB : ViewDataBinding> : AppCompatActivity(),
    BaseView {
    lateinit var binding: DB
    private var mPersenter: P? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, getLayoutId())
        setLight_White_Bar()
        if (mPersenter == null) {
            mPersenter = createPersenter()
        }
        if (mPersenter!=null){
            mPersenter!!.bindView(this as V)
        }

        if (isRegister()) {
            EventBus.getDefault().register(this)
        }
        initView()
        initData()
    }

    protected abstract fun getLayoutId(): Int
    protected abstract fun initView()
    protected abstract fun initData()
    protected abstract fun createPersenter(): P
    protected abstract fun isRegister(): Boolean

    fun getPersenter() = mPersenter

    override fun onDestroy() {
        super.onDestroy()
        mPersenter!!.unBindView()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun getMessage(message: EventModel<*>) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    open fun getMessageSticky(message: EventModel<*>) {

    }

    open fun postMsg(message: EventModel<*>) {
        EventBus.getDefault().post(message)
    }

    fun starActivity(clz:Class<*>){
        startActivity(Intent(this,clz))
    }
    fun getToken(): String? = SharedPreferencesUtils.getSaveToken(this, Constants.TOKEN)
    fun isTokenNotNull(): Boolean = !TextUtils.isEmpty(getToken())

    fun setLight_White_Bar(){
        StatusBarUtils.setStatusBar(this, View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR, R.color.white)
    }
    fun setLight_Red_Bar(){
        StatusBarUtils.setStatusBar(this, View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR, R.color.jx_red)
    }
}